/**
 *  @file StringBody.cpp
 */
#include "IHttpBody.h"
#include "../../../common/CppMemPool.h"
#include "../../../common/UtilFuncT.h"
#include "../../../convert/Convert.h"

using namespace cppflib::collections;

namespace cppflib
{

namespace net
{

namespace http
{

namespace message
{


StringBody::StringBody(void)
{
}

StringBody::StringBody(CFString * pInStr)
{
   this->pInStr = pInStr;
   cppmempool::Retain(this->pInStr);

   pStr = pInStr->ToUtf8String();
   cppmempool::Retain(pStr);
   SetContentLength(CFString::Strlen(pStr));
   SetContentType(_S("text/plain; charset=utf-8"));

   SetCurReadPos(0);
}

StringBody::~StringBody(void)
{
   cppmempool::Release(pInStr);
   cppmempool::Release(pStr);
}

int StringBody::Read(collections::ArrayByte &buffer)
{
   return Read(buffer, 0, static_cast<int>(buffer.GetSize()));
}

int StringBody::Read(collections::ArrayByte &buffer, int offset, int count)
{
   sz_t bytesLeft = static_cast<sz_t>(GetContentLength() - GetCurReadPos());
   if (bytesLeft == 0)
      return 0;

   if (count < 0 || offset < 0 || offset >= static_cast<int>(buffer.GetSize()))
      return 0;
  
   count = cppflib::Min<int>(count, static_cast<int>(buffer.GetSize() - offset));
   int bytesToCopy = cppflib::Min<int>(static_cast<int>(bytesLeft), count);

   buffer.CopyFrom(reinterpret_cast<u8_t*>(pStr), static_cast<u32_t>(GetContentLength()), offset, 
                   static_cast<u32_t>(GetCurReadPos()), bytesToCopy);
   AdvanceReadPos(bytesToCopy);
   return bytesToCopy;
}

int StringBody::Read()
{
   sz_t bytesLeft = static_cast<sz_t>(GetContentLength() - GetCurReadPos());
   if (bytesLeft == 0)
     return -1;

   int ret = pStr[GetCurReadPos()] & 0xff;
   AdvanceReadPos(1);
   return ret;
}
   

} // end of namespace message

} // end of namespace http

} // end of namespace net

} // end of namespace cppflib

